package player

import (
	"GameServer/Common/utils"

	"github.com/globalsign/mgo/bson"
	log "github.com/sirupsen/logrus"

	"GameServer/Common/data"
	"GameServer/Game/errors"
	"GameServer/Game/lib"
	"GameServer/Game/m"
	"GameServer/Game/sp"
	"GameServer/Game/union"
)

func (p *Player) UnionEnergySendsRequest(req *sp.UnionEnergySendsRequest) (res *sp.UnionEnergySendsResponse) {
	list := p.User.GetUnionEnergy().SendList()
	res = &sp.UnionEnergySendsResponse{
		List: lib.FormatUnionEnergySendSps(list),
	}
	return
}

// 工会玩家体力请求
func (p *Player) UnionEnergyReqRequest(req *sp.UnionEnergyReqRequest) (res *sp.UnionEnergyReqResponse) {
	us := p.User
	if us.Energy >= 50 {
		res = &sp.UnionEnergyReqResponse{
			Errcode: data.Errcode.ServerErr,
		}
		log.WithFields(log.Fields{
			"data":   us.Energy,
			"uid":    us.Uid.Hex(),
			"method": "UnionEnergyReqRequest",
		}).Warn("玩家体力过剩，不能够请求赠送")
		return
	}
	if us.UnionEnergyReqTime > utils.TNow().Unix() {
		res = &sp.UnionEnergyReqResponse{
			Errcode: data.Errcode.ServerErr,
		}
		return
	}

	ext := &m.ChatExt{Type: 2, Current: 0, Total: 5}

	err := union.UnionModule.UnionChatAll(us, "", ext.String(), BroadData)
	if err != nil {
		res = &sp.UnionEnergyReqResponse{
			Errcode: errors.ErrCode(err),
		}
		return
	}

	res = &sp.UnionEnergyReqResponse{
		ReqUnionEnergyTime: us.UnionEnergyReqTime,
	}
	return
}

// 工会玩家赠送体力
func (p *Player) UnionEnergyRequest(req *sp.UnionEnergyRequest) (res *sp.UnionEnergyResponse, err error) {
	tPlayer, ok := GetPlayerByUid(req.Uid)
	if !ok {
		log.WithFields(log.Fields{
			"data":   req,
			"uid":    p.User.Uid.Hex(),
			"method": "UnionEnergyRequest",
		}).Error("没有找到赠送的玩家对象")
		res = &sp.UnionEnergyResponse{
			Errcode: data.Errcode.ServerErr,
		}
		return
	}
	// 成就，记录工会体力赠送次数。
	lib.AddAchievProgress(p.User, data.AchievementType.Send_spins, 1)
	// 有成就完成，进行通知
	achLst := lib.AchievComplete(p.User)
	if len(achLst) > 0 {
		p.Send(&sp.AchievementNoticeRequest{
			Lst: achLst,
		})
	}
	tuUnionEnergy := tPlayer.User.GetUnionEnergy()

	if tuUnionEnergy.ReqMsg == nil || tuUnionEnergy.ReqMsg.Mid != req.Mid {
		mdata := make(map[string]interface{}, 0)
		mdata["req"] = req
		mdata["reqMsg"] = tuUnionEnergy.ReqMsg
		log.WithFields(log.Fields{
			"data":   mdata,
			"uid":    p.User.Uid.Hex(),
			"method": "UnionEnergyRequest",
		}).Error("消息id不一致")
		// 如果玩家赠送体力，可能存在旧的体力请求，该玩家可能退出公会，所以删除该体力请求
		m.DeleteUnionChatMsg(bson.ObjectIdHex(p.User.UnionId), req.Uid, req.Mid)
		res = &sp.UnionEnergyResponse{
			Errcode: data.Errcode.ServerErr,
		}
		return
	}

	recv, send, err := union.UnionModule.SendEnergy(p.User, req.Uid, req.Mid, tPlayer.User.UnionEnergyReqTime)
	if err != nil {
		res = &sp.UnionEnergyResponse{
			Errcode: errors.ErrCode(err),
		}
		return
	}
	res = &sp.UnionEnergyResponse{
		Info: lib.FormatUnionEnergySendSp(send),
	}
	utils.AsyncFunc(func() {
		tPlayer.UnionRecvEnergy(p, recv)
	})
	return
}

func (p *Player) UnionRecvEnergy(from *Player, recv *m.UnionEnergyRecv) {
	uProp, err := lib.UnionRecvEnergy(p.User, p.User.GetUnionEnergy(), recv, p.Send)
	if err != nil {
		mdata := make(map[string]interface{}, 0)
		mdata["fromUid"] = from.User.Uid.Hex()
		mdata["recv"] = recv
		log.WithFields(log.Fields{
			"data":   recv,
			"uid":    p.User.Uid.Hex(),
			"method": "UnionEnergyRequest",
		}).Error("收体力失败:", err)
		return
	}
	// 有成就完成，进行通知
	achLst := lib.AchievComplete(p.User)
	if len(achLst) > 0 {
		p.Send(&sp.AchievementNoticeRequest{
			Lst: achLst,
		})
	}
	union.UnionModule.UnionSendEnergyChat(p.User, p.User.GetUnionEnergy().ReqMsg, BroadData)

	p.UnionRecvEnergyNotice()
	// p.TimelyUpdateProp(req.GetType(), uProp)
	p.UpdateProp(new(sp.UnionEnergyInfoRequest).GetType(), uProp)

	if from == nil {
		return
	}
	req := &sp.UnionEnergyRequest{}

	// 战斗胜利给公会积分
	if from.User.UnionId != "" {
		uProp0, _, _, err := lib.GiveGoodsByKv("UnionRecvEnergy", from.User, m.BaseKV{Key: data.GlobalEnum.Union, Val: 1}, p.Send)
		if err != nil {
			log.WithFields(log.Fields{
				"data":   m.BaseKV{Key: data.GlobalEnum.Union, Val: 1},
				"uid":    from.User.Uid.Hex(),
				"method": "UnionRecvEnergy",
			}).Error("给公会积分失败")
		} else {
			// 有成就完成，进行通知
			achLst := lib.AchievComplete(p.User)
			if len(achLst) > 0 {
				p.Send(&sp.AchievementNoticeRequest{
					Lst: achLst,
				})
			}
			from.TimelyUpdateProp(req.GetType(), uProp)
			utils.AsyncFunc(func() {
				from.UpdateProp(req.GetType(), uProp0)
			})
		}
	}

	fromUnionEnergy := from.User.GetUnionEnergy()
	// 赠送体力同时是否还能够获得体力
	if !fromUnionEnergy.IsCanGetEnergy() {
		return
	}

	// 自己赠送体力，自己不扣体力，自己不增加体力。
	// uProp1, _, _, err := lib.GiveGoodsByKv("UnionEnergyRequest", from.User, m.BaseKV{Key: data.GlobalEnum.Energy, Val: -1})
	// if err != nil {
	// 	return
	// }

	// fromUnionEnergy.AddCanGetEnergy(1)

	// from.UpdateProp(req.GetType(), uProp1)
}

func (p *Player) UnionRecvEnergyNotice() {
	eEnergy := p.User.GetUnionEnergy()
	var list []*m.UnionEnergyRecv
	for _, item := range eEnergy.Recvs {
		if item.Status != 0 {
			continue
		}
		list = append(list, item)
	}

	if len(list) == 0 {
		return
	}
	res := &sp.UnionEnergyInfoRequest{
		Infos: lib.FormatUnionEnergyNoticeSps(list),
	}
	if p.Send(res) == nil {
		for _, item := range list {
			item.Status = 1
		}
	}
}
